import { QI_NIU_TOKEN } from '../app.config'
// 上传base64文件
export function uploadBase64Img (base64File) {
  return new Promise((resolve, reject) => {
    const pic = base64File.replace('"', '').split(',')[1]
    const url = 'http://upload.qiniup.com/putb64/-1' // 非华东空间需要根据注意事项 1 修改上传域名 -1表示不传文件大小
    const xhr = new XMLHttpRequest()
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        const result = JSON.parse(xhr.responseText)
        resolve(result.key)
      }
    }
    xhr.open('POST', url, true)
    xhr.setRequestHeader('Content-Type', 'application/octet-stream')
    xhr.setRequestHeader('Authorization', 'UpToken ' + QI_NIU_TOKEN)
    xhr.send(pic)
  })
}

/**
 * 上传文件
 * @param file
 * @param observer {next:fun,success:fun,error:fun}
 */
export function uploadImg (file, observer) {
  const config = {
    useCdnDomain: true
  }
  const qiniu = require('qiniu-js')
  const observable = qiniu.upload(file, new Date().getTime() + file.name, QI_NIU_TOKEN, null, config)
  observable.subscribe(observer)
}
